package com.lintesis.lintesismodel.common.hibernate;

import javax.persistence.Entity;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

@Entity
public class ConnectionManager
{

	private static final SessionFactory sessionFactory;
	private static Session session = null;

	static
	{
		try
		{
//			Locale.setDefault(new Locale("es", "ES"));
			sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

		} catch (Throwable ex)
		{
			// Log exception!
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static Session getSession() throws HibernateException
	{
		if (session == null || !session.isOpen())
		{
			session = sessionFactory.openSession();
			session.beginTransaction();
		}
		if (session.getTransaction().isActive() == false)
		{
			session.getTransaction().begin();
		}
		return session;

	}
	
	/**
	 * Returns a completly new hibernate session
	 * @return
	 * @throws HibernateException
	 */
	public static Session getNewSession() throws HibernateException
	{
			session = sessionFactory.openSession();
//			session.beginTransaction();
		return session;

	}
	
	

	public static StatelessSession getStatelessSession() throws HibernateException
	{
		return sessionFactory.openStatelessSession();
	}

	public static Transaction beginTransaction()
	{
		return ConnectionManager.getSession().beginTransaction();
	}

	public static void commit()
	{
		ConnectionManager.getSession().getTransaction().commit();
	}
}
